import { messageUtil } from '@jl/element-plus/utils';
import { useRequest } from '@jl/common/composable';
import { getVerifyCodeByEmail, resetPwdByEmail } from '@/api/user';
import { IEmail, IResetPwdByEmailParams, ISessionKey } from '@/api/user/types';

export function useFindPwd() {
  const {
    run: sendRun,
    data: sendData,
    error: sendError,
  } = useRequest<ISessionKey, IEmail>(getVerifyCodeByEmail, { sessionKey: '' });

  const {
    run: resetRun,
    error: resetError,
    loading: resetLoading,
  } = useRequest<any, IResetPwdByEmailParams>(resetPwdByEmail, {});

  const formRef = ref();
  const timer = ref<any>(null);
  const ruleForm = reactive({
    verifyCode: '',
    loginPwd: '',
    confirmLoginPwd: '',
    email: '',
  });
  const confirmPasswordValidate = (rule: any, value: any, callback: any) => {
    if (value !== ruleForm.loginPwd) {
      callback(new Error('和密码框输入不一致'));
    } else {
      callback();
    }
  };
  const rules = {
    loginPwd: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,12}$/,
        message: '密码校验不通过，8~12位数字+特殊字符+大小写字母组合',
        trigger: 'blur',
      },
    ],
    confirmLoginPwd: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: confirmPasswordValidate, trigger: 'blur' },
    ],
    email: [
      {
        required: true,
        message: '登录邮箱不能为空！',
      },
      {
        pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
        message: '邮箱格式错误',
        trigger: 'blur',
      },
    ],
    verifyCode: [
      {
        required: true,
        message: '验证码不能为空！',
      },
    ],
  };
  const seconds = ref<number>(120);
  const sendCode = async () => {
    if (!ruleForm.email) {
      messageUtil.warning('登录邮箱不能为空');
      return;
    }
    if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(ruleForm.email)) {
      messageUtil.warning('登录邮箱格式错误');
      return;
    }
    await sendRun({ data: { email: ruleForm.email } });
    console.log(sendError);
    if (!sendError.value) {
      messageUtil.success('验证码发送成功，请注意查收');
      timer.value = setInterval(() => {
        if (seconds.value === 0) {
          clearInterval(timer.value);
          timer.value = null;
          seconds.value = 120;
          return;
        }
        seconds.value--;
      }, 1000);
    }
  };
  const save = () => {
    formRef.value.validate(async (valid: boolean, fields: any) => {
      if (valid) {
        await resetRun({
          data: {
            loginPwd: ruleForm.loginPwd,
            sessionKey: sendData.value.sessionKey,
            verifyCode: ruleForm.verifyCode,
          },
        });
        if (!resetError.value) {
          messageUtil.success('找回密码成功');
          location.reload();
        }
      }
    });
  };

  return {
    formRef,
    ruleForm,
    rules,
    seconds,
    timer,
    resetLoading,
    sendCode,
    save,
  };
}
